import React, { useState, useEffect, useRef } from 'react';
import { Row, Col, Radio, Table, message, Select, DatePicker } from 'antd';
import services from 'src/services/api';
import { TIME_TYPE } from 'src/utils/constant';
import moment from 'moment';
moment.locale('zh-cn');
const { Option } = Select;
const { RangePicker } = DatePicker;

export default function RiskAnalyse() {
  const [data, setData] = useState([]);
  const [applications, setApplications] = useState([]);
  const [products, setProducts] = useState([]);
  const [events, setEvents] = useState([]);
  const [type, setType] = useState(3);
  const [params, setParams] = useState({
    app_id: undefined,
    product_id: undefined,
    event_ids: [],
  });
  const [date, setDate] = useState({
    start_time: moment()
      .startOf('week')
      .format('YYYY-MM-DD HH:mm'),
    end_time: moment().format('YYYY-MM-DD HH:mm'),
  });
  const paramsRef = useRef(params);
  paramsRef.current = params;
  const dateRef = useRef(date)
  dateRef.current = date

  useEffect(() => {
    getApps();
    getProducts();
  }, []);

  // 获取渠道
  function getApps() {
    services.application.getAppCodeList({}).then((res) => {
      if (res.code === 0) {
        setApplications(res.data);
      }
    });
  }

  // 获取产品
  function getProducts() {
    services.product.getProductCodeList().then((res) => {
      if (res.code === 0) {
        setProducts(res.data);
      }
    });
  }

  // 获取事件
  function getEvents({ app_id, product_id }) {
    services.event.getEventCodeList({ app_id, product_id }).then((res) => {
      if (res.code === 0) {
        setEvents(res.data);
      }
    });
  }

  function getData(paramsState, dateParams, type) {
    setType(type)
    let params = { ...paramsState, ...dateParams, type };
    if (!params.product_id) params.product_id = 0;
    if (params.type) {
      if (params.event_ids.length !== 1) return;
    } else {
      if (params.event_ids.length <= 1) return;
    }
    if (!params.app_id) {
      return message.warning('请选择渠道');
    }
    if (!params.start_time || !params.end_time) {
      return message.warning('请选择统计时间');
    }

    services.statistics.riskAnalyse(params).then((res) => {
      if (res.code === 0) {
        setData(res.data);
      } else {
        message.warning(res.msg);
        setData([])
      }
    });
  }

  useEffect(() => {
    const type = params.event_ids.length > 1 ? null : 3
    setType(type)
    getData(params, date, type);
  }, [params]);

  function onAppChangeSelect(app_id) {
    getEvents({ app_id, product_id: paramsRef.current.product_id });
    setParams((params) => ({ ...params, event_ids: [] }));
    setData([]);
  }

  function onProductChangeSelect(product_id) {
    getEvents({ app_id: paramsRef.current.app_id, product_id });
    setParams((params) => ({ ...params, event_ids: [] }));
    setData([]);
  }

  function onEventChangeSelect(event_ids) {
    if (event_ids.length > 5) {
      throw '最多选择5个事件';
    }
    setParams((params) => ({ ...params, event_ids: event_ids }))
    if (event_ids.length === 0) {
      setData([]);
    }
  }

  function paramsChange(name, value, cb) {
    setParams((params) => ({ ...params, [name]: value }));
    cb && cb();
  }

  function dateChange(time, timeString) {
    setDate({
      start_time: timeString[0],
      end_time: timeString[1],
    });
  }

  function dateOk() {
    window.setTimeout(() => {
      getData(params, dateRef.current, type)
    }, 0)
  }

  const columns = [
    {
      title: '统计时间',
      key: 'time',
      dataIndex: 'time',
    },
    {
      title: '事件',
      key: 'event_name',
      dataIndex: 'event_name',
    },
    {
      title: '所属产品',
      key: 'product_name',
      dataIndex: 'product_name',
    },
    {
      title: '请求总量',
      key: 'total',
      dataIndex: 'total',
    },
    {
      title: '通过请求量',
      key: 'pass',
      dataIndex: 'pass',
    },
    {
      title: '通过占比',
      key: 'pass_percentage',
      dataIndex: 'pass_percentage',
      render: (text) => text + '%',
    },
    {
      title: '复核请求量',
      key: 'review',
      dataIndex: 'review',
    },
    {
      title: '复核占比',
      key: 'review_percentage',
      dataIndex: 'review_percentage',
      render: (text) => text + '%',
    },
    {
      title: '拒绝请求量',
      key: 'reject',
      dataIndex: 'reject',
    },
    {
      title: '拒绝占比',
      key: 'reject_percentage',
      dataIndex: 'reject_percentage',
      render: (text) => text + '%',
    },
  ];

  return (
    <div>
      <Row type='flex' gutter={10} justify='end'>
        <Col className='gutter-row filter-item'>
          <Select
            className='prop-select'
            onChange={(value) => {
              paramsChange('app_id', value, onAppChangeSelect(value));
            }}
            value={params.app_id}
            style={{ width: 150 }}
            allowClear={true}
            placeholder='请选择渠道'
          >
            {applications.map((item) => {
              return (
                <Option value={item.app_id} key={item.app_id}>
                  {item.app_name}
                </Option>
              );
            })}
          </Select>
        </Col>

        <Col className='gutter-row filter-item'>
          <Select
            className='prop-select'
            onChange={(value) => {
              paramsChange('product_id', value, onProductChangeSelect(value));
            }}
            value={params.product_id}
            style={{ width: 150 }}
            allowClear={true}
            placeholder='请选择产品'
          >
            {products.map((item) => {
              return (
                <Option value={item.product_id} key={item.product_id}>
                  {item.product_name}
                </Option>
              );
            })}
          </Select>
        </Col>

        <Col className='gutter-row filter-item'>
          <Select
            className='prop-select'
            onChange={(value) => {
              paramsChange('event_ids', value, onEventChangeSelect(value));
            }}
            value={params.event_ids}
            style={{ width: 300 }}
            allowClear={true}
            placeholder='请选择事件'
            mode='multiple'
            showArrow={true}
          >
            {events.map((item) => {
              return (
                <Option value={item.event_id} key={item.event_id}>
                  {item.event_name}
                </Option>
              );
            })}
          </Select>
        </Col>

        <Col className='gutter-row filter-item' span={8}>
          <RangePicker
            showTime={{ defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')] }}
            format='YYYY-MM-DD HH:mm'
            placeholder={['起始时间', '结束时间']}
            onChange={dateChange.bind(this)}
            onOk={dateOk.bind(this, params, date, type)}
            style={{ width: '100%' }}
            disabledDate={(current) => current > moment().endOf('day')}
            ranges={{
              本周: [moment().startOf('week'), moment()],
              近7天: [moment().subtract('days', 6), moment()],
              本月: [moment().startOf('month'), moment()],
              近30天: [moment().subtract('days', 29), moment()],
            }}
            value={date.start_time ? [moment(date.start_time), moment(date.end_time)] : null}
          />
        </Col>
      </Row>
      {type && (
        <div style={{ margin: '20px 0 0 0' }}>
          <Row type='flex' justify='end'>
            <Col>
              <Radio.Group value={type} buttonStyle='solid' onChange={(e) => getData(params, date, e.target.value, true)}>
                {TIME_TYPE.map((it) => {
                  return (
                    <Radio.Button value={it.key} key={it.key}>
                      {it.value}
                    </Radio.Button>
                  );
                })}
              </Radio.Group>
            </Col>
          </Row>
        </div>
      )}
      <div className='inner-content'>
        <Table
          columns={columns}
          dataSource={data}
          rowKey={(record, index) => index}
          style={{ margin: '20px 0 0 0' }}
          pagination={{
            showQuickJumper: true,
            total: data.length,
            showTotal: (total) => {
              return `总共 ${total} 条`;
            },
            showSizeChanger: true,
            pageSizeOptions: ['5', '10', '15', '20']
          }}
        />
      </div>
    </div>
  );
}
